package com.bk.dao;

import com.bk.model.Book;
import com.bk.model.User;
import com.bk.util.DbUtil;
import com.bk.util.ToolUtil;

import javax.swing.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Ayi
 */
public class BorrowDao {
    // 获取数据库中的借阅表，以结果集返回
    public ResultSet getBorrowTable(User user) throws SQLException {
        Connection connection = DbUtil.getConnection();
        String sql = "select * from borrow where uid = ?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, user.getUid());
        ResultSet rs = ps.executeQuery();
        System.out.println(user.getUid());
        return rs;
    }

    // 往借阅表添加记录 借书
    public boolean addBorrowTable(User user, Book book) throws SQLException {
        Connection connection = DbUtil.getConnection();
        String sql = "select * from borrow where bid = ?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, Integer.toString(book.getBid()));
        ResultSet rs = ps.executeQuery();
        // 更新数据库
        if (!new BookDao().updateSubBook(book)) {
            JOptionPane.showMessageDialog(null, "这本书被借光啦");
            return false;
        }
        new BookTypeDao().updateSubBookType(book);
        // 若已借阅此书，借阅量 + 1
        if (rs.next()) {
            String sql0 = "update borrow set uborrow = ? where bid = ?";
            PreparedStatement ps0 = connection.prepareStatement(sql0);
            int currentBorrowNums = Integer.valueOf(rs.getString("uborrow"));
            ps0.setString(1, Integer.toString(currentBorrowNums + 1));
            ps0.setString(2, Integer.toString(book.getBid()));
            return ps0.executeUpdate() > 0 ? true : false;
        } else {// 否则生成新的借阅记录
            String sql1 = "insert into borrow values (?, ?, ?, ?, ?, ?, ?)";
            PreparedStatement ps1 = connection.prepareStatement(sql1);
            ps1.setString(1, user.getUid());
            ps1.setString(2, Integer.toString(book.getBid()));
            ps1.setString(3, book.getBname());
            ps1.setString(4, book.getBtype());
            ps1.setString(5, "1");
            ps1.setString(6, new ToolUtil().getDate());
            ps1.setString(7, "10分钟");
            return ps1.executeUpdate() > 0 ? true : false;
        }
    }

    // 从借阅表删除记录 还书
    public boolean deleteBorrowTable(String idOrNameInfo, Book book) throws SQLException {
        Connection connection = DbUtil.getConnection();
        // 根据id或书名
        if (new ToolUtil().judgeIdOrName(idOrNameInfo)) {
            // 更新数据库
            String sql = "select * from borrow where bid = " + idOrNameInfo;
            PreparedStatement ps = connection.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                int uborrow = Integer.valueOf(rs.getString("uborrow"));
                new BookDao().updateAddBook(book, uborrow);
                new BookTypeDao().updateAddBookType(book, uborrow);
            }
            // 删除借阅记录
            String sql0 = "delete from borrow where bid = " + idOrNameInfo;
            PreparedStatement ps0 = connection.prepareStatement(sql0);
            return ps0.executeUpdate() > 0 ? true : false;
        } else {
            // 更新数据库
            String sql = "select * from borrow where bid = ?";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, "《" + idOrNameInfo + "》");
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                int uborrow = Integer.valueOf(rs.getString("uborrow"));
                new BookDao().updateAddBook(book, uborrow);
                new BookTypeDao().updateAddBookType(book, uborrow);
            }
            // 删除借阅记录
            String sql1 = "delete from borrow where bname = ?";
            PreparedStatement ps1 = connection.prepareStatement(sql1);
            ps1.setString(1, "《" + idOrNameInfo + "》");
            return ps1.executeUpdate() > 0 ? true : false;
        }
    }

    // 刷新死亡时间
    public User updateDeadlineTime(User user) throws SQLException, ParseException {
        // 获取当前时间
        long currentTime = System.currentTimeMillis();
        // 获取表内所有借阅时间
        Connection connection = DbUtil.getConnection();
        String sql = "select * from borrow where uid = ?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, user.getUid());
        ResultSet rs = ps.executeQuery();
        // 依次更新期限剩余
        while (rs.next()) {
            String sqlu = "update borrow set deadlinetime = ? where bid = ?";
            PreparedStatement psu = connection.prepareStatement(sqlu);
            psu.setString(2, rs.getString("bid"));
            // 获取当前行时间
            String str = rs.getString("starttime");
            Date date = new SimpleDateFormat("yyyy年MM月dd日HH时mm分").parse(str);
            long time = date.getTime();
            // 计算差值化成分钟更新
            long updateTime = (currentTime - time) / (1000 * 60);
            int ut = 10 - (int)updateTime;
            if (ut > 0) {
                psu.setString(1, Integer.toString(ut) + "分钟");
            }else {
                psu.setString(1, "(您已逾期)");
            }
            psu.executeUpdate();
        }
        // 同步信用更新
        user.setUcredit(updateCredit(user));
        return user;
    }

    // 更新信用
    private String updateCredit(User user) throws SQLException {
        Connection connection = DbUtil.getConnection();
        String sql = "select * from borrow where uid = ?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, user.getUid());
        ResultSet rs = ps.executeQuery();
        int count = 0;
        while (rs.next()) {
            if (rs.getString("deadlinetime").equals("(您已逾期)")) {
                count++;
            }
        }
        String ucr;
        if (count == 0) {
            ucr = "优秀";
        }else if (count > 0 && count < 2) {
            ucr = "良好";
        }else if (count < 3) {
            ucr = "较差";
        }else {
            ucr = "非常差";
        }
        String sqlu = "update user set ucredit = ? where uid = ?";
        PreparedStatement psu = connection.prepareStatement(sqlu);
        psu.setString(1, ucr);
        psu.setString(2, user.getUid());
        psu.executeUpdate();
        return ucr;
    }
}
